﻿using AutoMapper;
using AutoMapper.Internal.Mappers;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MiniExcelLibs;
using Serilog;
using SheepStorage.API.Application.Command.ProviderManageCommand;
using SheepStorage.API.Baseclass;
using SheepStorage.Domain.Dto.InputDto;
using SheepStorage.Domain.Dto.Output;
using SheepStorage.Domain.DTO.Output;
using SheepStorage.Domain.Entity;
using SheepStorage.Repository.Interface;
using SheepStorage.Service.Interface;
using Yitter.IdGenerator;

namespace SheepStorage.API.Controllers
{
    /// <summary>
    /// 供应商管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [AllowAnonymous]
    public class ProviderManageController : ControllerBase
    {
        /// <summary>
        /// 中介者模式
        /// </summary>
        private readonly IMediator _mediator;



        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mediator">中介者模式</param>
        public ProviderManageController(IMediator mediator)
        {
            _mediator = mediator;
        }


        /// <summary>
        /// 生成雪花编号
        /// </summary>
        /// <param name="count">数量</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetSnowId(int count)
        {
            try
            {
                List<long> longs = new List<long>();

                for (int i = 0; i <= count; i++)
                {
                    var snowId = YitIdHelper.NextId();
                    longs.Add(snowId);
                }

                return Ok(longs);
            }
            catch (Exception ex)
            {
                Log.Error("生成雪花编号出错" + ex.Message);
                throw;
            }
            
        }

        #region  数据导出

        ///// <summary>
        ///// 数据导出
        ///// </summary>
        ///// <param name="command"></param>
        ///// <returns></returns>
        //[HttpGet("/ExportCustomer")]
        //public async Task<IActionResult> ExportCustomer([FromQuery] ProviderManageSelectCommand command)
        //{
        //    //获取数据列表
        //    var list = await _mediator.Send(command);

        //    //获取数据
        //    var data = list.Data;

        //    //转换为导出类型
        //    var exportCustomerDto = _mapper.Map<List<ProviderManage>, List<ProviderManageInput>>(data);

        //    // 创建一个内存流对象
        //    MemoryStream ms = new MemoryStream();

        //    // 异步将导出的客户数据保存到内存流中
        //    await ms.SaveAsAsync(exportCustomerDto);

        //    // 将内存流的读取位置重置到开始位置
        //    ms.Seek(0, SeekOrigin.Begin);

        //    // 返回一个文件流结果，指定内容类型和文件下载名
        //    return new FileStreamResult(ms, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
        //    {
        //        FileDownloadName = "客户信息.xlsx"
        //    };
        //}

        #endregion



        /// <summary>
        /// 数据导出
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> ExportCustomer([FromQuery] PageInput input)
        {
            try
            {
                var list = new ProviderManageExportCommand(input);
                return await _mediator.Send(list);
            }
            catch (Exception ex)
            {
                Log.Error("数据导出出错" + ex.Message);
                throw;
            }
            
        }


        /// <summary>
        /// 数据导入
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Results<int>> ImportExcel(IFormFile file)
        {
            try
            {
                var command = new ProviderManageImportCommand(file);

                return await _mediator.Send(command);
            }
            catch (Exception ex)
            {
                Log.Error("数据导入出错" + ex.Message);
                throw;
            }
            
        }


        #region  数据导入

        ///// <summary>
        ///// 数据导入
        ///// </summary>
        ///// <param name="file"></param>
        ///// <returns></returns>
        //[HttpPost("/ImportExcel")]
        //public async Task<Results<bool>> ImportExcel(IFormFile file)
        //{
        //    try
        //    {
        //        // 读取文件内容
        //        MemoryStream memoryStream = new MemoryStream();
        //        //将传进来的文件拷贝到内存流中
        //        file.CopyTo(memoryStream);
        //        //通过内存流读取文件内容
        //        var list = await memoryStream.QueryAsync<ProviderManageOutput>();

        //        // 转换为实体
        //        var provider = _mapper.Map<List<ProviderManageOutput>, List<ProviderManage>>(list.ToList());

        //        //批量添加
        //        foreach (var item in provider)
        //        {
        //            var provider1 = _mapper.Map<ProviderManageCreateCommand>(item);
        //            await AddProviderManage(provider1);
        //        }

        //        return Results<bool>.DataResult(true);
        //    }
        //    catch (Exception)
        //    {
        //        throw;
        //    }
        //}


        #endregion





        /// <summary>
        /// 供应商列表
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Results<PageOutput<ProviderManage>>> GetProviderManage(ProviderManageSelectCommand command)
        {
            try
            {
                return await _mediator.Send(command);
            }
            catch (Exception ex)
            {
                Log.Error("供应商列表出错" + ex.Message);
                throw;
            }
            
        }


        /// <summary>
        /// 供应商添加
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Results<int>> AddProviderManage([FromForm] ProviderManageCreateCommand command)
        {
            try
            {
                return await _mediator.Send(command);
            }
            catch (Exception ex)
            {
                Log.Error("供应商添加出错" + ex.Message);
                throw;
            }
            
        }

        /// <summary>
        /// 批量删除/逻辑删除
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<Results<int>> DeleteProviderManage(ProviderManageDeleteCommand command)
        {
            try
            {
                return await _mediator.Send(command);
            }
            catch (Exception ex)
            {
                Log.Error("逻辑删除出错" + ex.Message);
                throw;
            }
            
        }

        /// <summary>
        /// 获取单条数据
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Results<ProviderManage>> GetProviderManageInfo([FromQuery] ProviderManageFindCommand command)
        {
            try
            {
                return await _mediator.Send(command);
            }
            catch (Exception ex)
            {
                Log.Error("获取单条数据出错" + ex.Message);
                throw;
            }
            
        }



    }
}
